const {BrowserWindow, Menu, ipcMain} = require('electron/main')
const path = require('node:path')
const userData = require('../global/globalUserData')
const Config = require('../global/Config')

module.exports = ()=>{
    const win = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
            preload: path.join(__dirname, './../preload/preload_welcome.js'),
            nodeIntegration: false,
            contextIsolation: true,
            scrollBounce: false,
        }
    })

    // 禁用滚动条
    win.webContents.executeJavaScript(`document.body.style.overflow = 'hidden';`);

    // 禁用最大化
    // win.maximizable = false;

    win.loadFile(path.join(__dirname, './../Page/ChatPage/Chat.html')).then(()=>{
        win.setTitle("myIM");
        
        // 发送获取好友列表请求
        fetch(`http://${Config.HOST}:${Config.PORT}/GetInfo`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                userId: userData.getUserId()
            })
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            console.log(data)
            if (data.code === '0000') {
                win.webContents.send('update-contact-list', data.messages);
            } else {
                console.error('获取好友列表失败:', data.msg);
                win.webContents.send('update-contact-list', []);
            }
        })
        .catch(error => {
            console.error('获取好友列表失败:', error);
            win.webContents.send('update-contact-list', []);
        });
    })

    // 删除原始顶部菜单栏
    const menu = Menu.buildFromTemplate([])
    Menu.setApplicationMenu(menu)

    // // 监听开发者工具事件
    // ipcMain.on('open-devtools', () => {
    //     console.log('收到打开开发者工具请求');
    //     win.webContents.openDevTools();
    // });
    //
    // // 也可以直接在窗口加载完成后打开
    // win.webContents.on('did-finish-load', () => {
    //     console.log('窗口加载完成，打开开发者工具');
    //     win.webContents.openDevTools();
    // });
}